package com.lzy.cloud.search.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lzy.cloud.search.client.entity.EsQuery;
import com.lzy.cloud.search.client.service.StructuringAggregationsService;
import com.lzy.cloud.search.client.util.EsClient;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 结构化聚合
 */
@Service
public class StructuringAggregationsServiceImpl implements StructuringAggregationsService {

    @Autowired
    private EsClient client;

    public void testStructuringAggregations(EsQuery esQuery)   {
        SearchResponse sr = client.getConnection().prepareSearch()
                .addAggregation(
                        AggregationBuilders.terms("user").field("kimchy")  //
                                .subAggregation(AggregationBuilders.dateHistogram("by_year")
                                                .field("postDate")
                                                .dateHistogramInterval(DateHistogramInterval.YEAR)
//                                        .subAggregation(AggregationBuilders.avg("avg_children").field("children"))
                                )
                )
                .execute().actionGet();

        SearchHit[] searchHits = sr.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            System.out.println(JSON.toJSONString(searchHit.getSourceAsString(), SerializerFeature.PrettyFormat));
        }
    }

}
